<template>
  <div>
    <a-modal :width="500" title="绑定邮箱" v-model="visible" @ok="handleOk">
      <div class="error mb10">
        请您注意：1分钟只能发送1次验证码，验证码5分钟内有效
      </div>
      <div class="wfull">
        <a-row class="mb10">
          <a-col :span="4">邮箱地址</a-col>
          <a-col :span="20">
            <ZgInput placeholder="请输入电子邮箱地址" v-model="email"></ZgInput>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4">验证码</a-col>
          <a-col :span="12">
            <ZgInput placeholder="验证码" v-model="code"></ZgInput>
          </a-col>
          <a-col :span="8">
            <a-button type="primary" :disabled="sending" @click="sendEmail">
              <div v-if="sending">{{ time }} 秒后可再次发送</div>
              <div v-else><i class="fa fa-plane mr5"/>获取验证码</div>
            </a-button>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      sending: false,
      task: null,
      time: 60,
      email: '',
      code: ''
    }
  },
  mounted () {
  },
  methods: {
    open () {
      this.visible = true
    },
    close () {
      this.visible = false
    },
    sendEmail () {
      if (this.email.length === 0) {
        this.$warning({ title: '请输入电子邮箱地址' })
        return
      }
      this.$http.post('/zg-system/user/email/send', this.email, () => {
        this.sending = true
        this.task = setInterval(() => {
          if (this.time > 0) {
            this.time = this.time - 1
          } else {
            clearInterval(this.task)
            this.sending = false
            this.time = 60
          }
        }, 1000)
      })
    },
    handleOk () {
      if (this.email.length === 0) {
        this.$warning({ title: '请输入电子邮箱地址' })
        return
      }
      if (this.code.length === 0) {
        this.$warning({ title: '请输入验证码' })
        return
      }
      this.$http.post('/zg-system/user/email/bind', {
        email: this.email,
        code: this.code
      }, () => {
        clearInterval(this.task)
        this.sending = false
        this.time = 60
        this.close()
        this.$info({ title: '操作成功！' })
        this.$emit('ok', this.email)
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
